#pragma once

#include <iostream>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#define ROOT "./"
#define devnull "/dev/null"

void Daemon(bool ischdir, bool isclose)
{
    signal(SIGCHLD, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);

    if (fork() > 0)
        exit(0);
    setsid();
    if (ischdir)
    {
        chdir(ROOT);
    }
    if (isclose)
    {
        close(0);
        close(1);
        close(2);
    }
    else
    {
        int fd = open(devnull, O_WRONLY);
        if (fd > 0)
        {
            dup2(fd, 1);
            dup2(fd, 0);
            dup2(fd, 2);
            close(fd);
        }
    }
}